from constants import *
from datetime import timedelta
import os
import urllib
import urllib2

from myuser import *

def authorise(role):
    def wrapper(f):
        def deco(self, * args, ** kwargs):
            user = MyUser()
            if role == USER_ANY and not user.loggedIn:
                self.redirect("/main/login?message=You must be logged in to view this page")
            elif role == USER_TENANT and not user.tenant:
                self.redirect("/?message=You must be logged in as a tenat to view this page")
            elif role == USER_LANDLORD and not user.landlord:
                self.redirect("/?message=You must be logged in as a landlord to view this page")
            elif role == USER_ADMIN and not user.admin:
                self.redirect("/?message=You must be logged in as an admin to view this page")
            else:
                message = self.request.get("message")
                data = {'user': user, "host": getHostUrl()}
                if message:
                    data['message'] = message
                kwargs['data'] = data
                f(self, * args, ** kwargs)
        return deco
    return wrapper

def handleTime(datetime):
    if datetime is not None:
        kenyantime = timedelta(hours=3)
        return str(datetime + kenyantime)[:-7]
    else:
        return ""
def sendMessage(sender, recepient, message):
    url = "http://cymoxpost.appspot.com/sakwapost"
    values = {'source': sender,
        'destination': recepient,
            'message': message}
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
    msg = Message()
    msg.source = sender
    msg.destination = recepient
    msg.message = message
    msg.response = the_page
    msg.put()

def newHouseId():
    m = db.GqlQuery("SELECT * FROM House order by houseId desc limit 1")
    newId = 0
    for ob in m:
        newId = ob.houseId + 1
        break
    return newId
def houseBooked(houseId):
    m = db.GqlQuery("SELECT * FROM Booking where houseId = " + houseId + " and status='pending'")
    total = 0
    for ob in m:
        total = total + 1
    if total > 0:
        return "<a href='/landlord_bookings?houseId=" + houseId + "'>" + str(total) + " Bookings</a>"
    else:
        return "None"

def getHostUrl():
    if os.environ.get('HTTP_HOST'):
        return os.environ['HTTP_HOST']
    else:
        return os.environ['SERVER_NAME']